package managesystem;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class addBuddyServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	/**
	 * Afhandelen van de informatie van het formulier
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse resp) {
		HttpSession session = req.getSession();
		Student currStud = (Student) session.getAttribute("currStud");
		String firstName = req.getParameter("firstName").trim();
		String lastName = req.getParameter("lastName").trim();
		String error = "This student is already your buddy.";
		boolean foundBuddy = false;
		boolean valid = false;
		if(firstName.length() != 0 && firstName.contains(" ") == false && lastName.length() != 0 && lastName.contains(" ") == false){
			valid = true;
			List<Buddy> buddies = currStud.getBuddies();
			for(Iterator<Buddy> it = buddies.iterator(); it.hasNext();) {
				Buddy b = it.next();
				if(b.getFirstname().equals(firstName) && b.getLastname().equals(lastName)) {
					foundBuddy = true;
				}
			}
		}
		else{
			error = "You didn't fill in a name or you have fill in a space in a name.";
			//System.out.println("in error fill name geraakt");
		}
		
		if(valid == false){
			session.setAttribute("error",error );
		}
		else {if(foundBuddy == true){
			session.setAttribute("error",error );
		}
			else {
				Buddy buddy = new Buddy(firstName, lastName);
				currStud.addBuddy(buddy);
				session.setAttribute("message", "A new buddy "+buddy.getFirstname()+" "+buddy.getLastname()+" is added succesfully.");
				session.setAttribute("currStud", currStud);
				StudentManager.add(currStud);
			}
		}
		try {
			String fromMobile = (String) session.getAttribute("fromMobile");
			if(fromMobile.equals("true")){
				resp.sendRedirect("/index-mobile.jsp");
			}
			else{
				resp.sendRedirect("/index.jsp?id=dashboard");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


